/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import me.zhengjie.config.exception.WeChatException;
import me.zhengjie.constant.ConstantUtils;
import me.zhengjie.modules.system.domain.CourseClock;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.system.domain.CourseManagerRequest;
import me.zhengjie.modules.system.domain.CourseManagerResponse;
import me.zhengjie.modules.system.service.CourseClassService;
import me.zhengjie.modules.system.service.CourseClockConfigService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.repository.CourseClockRepository;
import me.zhengjie.modules.system.service.CourseClockService;
import me.zhengjie.modules.system.service.mapstruct.CourseClockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author 王宇
* @date 2023-09-16
**/
@Service
@RequiredArgsConstructor
public class CourseClockServiceImpl implements CourseClockService {

    private final CourseClockRepository courseClockRepository;
    private final CourseClockMapper courseClockMapper;

    @Autowired
    private CourseClassService courseClassService;

    @Autowired
    private CourseClockConfigService courseClockConfigService;

    @Override
    public Map<String,Object> queryAll(CourseClockQueryCriteria criteria, Pageable pageable){
        Page<CourseClock> page = courseClockRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        Map<String, Object> resultMap = PageUtil.toPage(page.map(courseClockMapper::toDto));
        for (CourseClockDto obj : (List<CourseClockDto>)resultMap.get("content")) {
            String userName = obj.getUserName();
            if (StringUtils.isNotBlank(userName)){
                obj.setNickName(userName);
            }
        }
        return resultMap;
    }

    @Override
    public List<CourseClockDto> queryAll(CourseClockQueryCriteria criteria){
        return courseClockMapper.toDto(courseClockRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public CourseClockDto findById(Long clockId) {
        CourseClock courseClock = courseClockRepository.findById(clockId).orElseGet(CourseClock::new);
        ValidationUtil.isNull(courseClock.getClockId(),"CourseClock","clockId",clockId);
        return courseClockMapper.toDto(courseClock);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CourseClockDto create(CourseClock resources) {
        if(courseClockRepository.findByClockNo(resources.getClockNo()) != null){
            throw new EntityExistException(CourseClock.class,"clock_no",resources.getClockNo());
        }
        return courseClockMapper.toDto(courseClockRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(CourseClock resources) {
        CourseClock courseClock = courseClockRepository.findById(resources.getClockId()).orElseGet(CourseClock::new);
        ValidationUtil.isNull( courseClock.getClockId(),"CourseClock","id",resources.getClockId());
        CourseClock courseClock1 = null;
        courseClock1 = courseClockRepository.findByClockNo(resources.getClockNo());
        if(courseClock1 != null && !courseClock1.getClockId().equals(courseClock.getClockId())){
            throw new EntityExistException(CourseClock.class,"clock_no",resources.getClockNo());
        }
        courseClock.copy(resources);
        courseClockRepository.save(courseClock);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long clockId : ids) {
            courseClockRepository.deleteById(clockId);
        }
    }

    @Override
    public void download(List<CourseClockDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (CourseClockDto courseClock : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("打卡编号", courseClock.getClockNo());
            map.put("课程编号", courseClock.getCourseNo());
            map.put("打卡班级", courseClock.getClockClass());
            map.put("编辑编号", courseClock.getClassNo());
            map.put("微信昵称", courseClock.getNickName());
            map.put("手机号", courseClock.getMobile());
            map.put("openid", courseClock.getOpenId());
            map.put("打卡时间", courseClock.getCreateTime());
            map.put("0待审核，1：审核通过，2：不通过，3：优秀", courseClock.getStatus());
            map.put("内容", courseClock.getClockContent());
            map.put("更新时间", courseClock.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public CourseManagerResponse manager(CourseManagerRequest request) {
        if (StringUtils.isBlank(request.getClassNo())){
            throw new WeChatException("缺少参数");
        }
        CourseClassQueryCriteria classQueryCriteria = new CourseClassQueryCriteria();
        classQueryCriteria.setClassNo(request.getClassNo());
        classQueryCriteria.setStatus(ConstantUtils.Valid);
        List<CourseClassDto> list = courseClassService.queryAll(classQueryCriteria);
        if (CollectionUtils.isEmpty(list)){
            throw new WeChatException("班级不存在");
        }
        CourseClassDto courseClassDto = list.get(0);

        CourseClockConfigQueryCriteria configQueryCriteria = new CourseClockConfigQueryCriteria();
        configQueryCriteria.setCourseNo(courseClassDto.getCourseNo());
        List<CourseClockConfigDto> courseClockConfigDtos = courseClockConfigService.queryAll(configQueryCriteria);
        if (CollectionUtils.isEmpty(courseClockConfigDtos)){
            throw new WeChatException("课程打开配置未配置");
        }
        CourseClockConfigDto courseClockConfigDto = courseClockConfigDtos.get(0);
        CourseManagerResponse response = new CourseManagerResponse();

        response.setClassNo(courseClassDto.getClassNo());
        response.setClassName(courseClassDto.getName());
        response.setClassCount(courseClassDto.getStudentNumber());
        response.setStartDate(DateUtil.getTimeStamp(courseClockConfigDto.getStartDate()));
        response.setEndDate(DateUtil.getTimeStamp(courseClockConfigDto.getEndDate()));

        List<CourseManagerResponse.ManagerDetail> managerDetails = new ArrayList<>();

        CourseClockQueryCriteria courseClockQueryCriteria = new CourseClockQueryCriteria();
        courseClockQueryCriteria.setCourseNo(courseClassDto.getCourseNo());
        List<CourseClockDto> courseClockDtoList = queryAll(courseClockQueryCriteria);
        if (!CollectionUtils.isEmpty(courseClockDtoList)) {
            Map<Timestamp, Long> userClockList = courseClockDtoList.parallelStream().collect(Collectors.groupingBy(CourseClockDto::getCreateTime,Collectors.counting()));
            userClockList.forEach((k,v) -> {
                CourseManagerResponse.ManagerDetail detail = new CourseManagerResponse.ManagerDetail();
                detail.setClockDate(DateUtil.getTimeStamp(k));
                detail.setClockNumber(v);
                managerDetails.add(detail);
            });
        }
        response.setDetail(managerDetails);
        return response;
    }
}